// index.js
import { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import { login } from "@/api/api.js";

const LOGIN_SUCCESS_CODE = '200';
const UNAUTHORIZED_CODE = '401';

export default createStore({
    state: {
        username: null, // 存放用户姓名
        account: null, // 存放用户账号
        userType: null, // 存放用户类型
        isAuthenticated: false, // 用户是否已认证
    },
    mutations: {
        setUser(state, { username, account, userType }) {
            state.username = username;
            state.account = account;
            state.userType = userType;
            state.isAuthenticated = true;
            window.location.reload();
        },
        logout(state) {
            state.username = null;
            state.account = null;
            state.userType = null;
            state.isAuthenticated = false;
            window.location.reload();
        },
    },
    actions: {
        async loginUser({ commit }, userData) {
            try {
                const response = await login(userData);
                console.log(response);

                if (response.data.code === LOGIN_SUCCESS_CODE) {
                    const { username, account, userType } = response.data.resultData;
                    commit('setUser', { username, account, userType });
                } else if (response.data.code === UNAUTHORIZED_CODE) {
                    alert(response.data.msg);
                } else {
                    console.error('Login failed:', response.data.msg);
                }

                console.log(this.state);
            } catch (error) {
                console.error('An error occurred during login:', error);
                throw error; // 重新抛出错误，以便在组件中处理
            }
        },
        logoutUser({ commit }) {
            // 在这里添加清除本地存储的逻辑，例如：localStorage.removeItem('vuex');
            commit('logout');
        },
    },
    getters: {
        // 在需要时添加 getter
    },
    plugins: [
        createPersistedState({
            storage: window.localStorage
        })
    ]
});
